﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models;
using Infrastructure.Data;

namespace Keepo.Helpers
{
    //this Attribute will be executed for each user's request
    public class CookieGuidAttribute : ActionFilterAttribute
    {
        const int UserCategoryId = 1;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var Request = filterContext.HttpContext.Request;
            var Response = filterContext.HttpContext.Response;

            //if no GUID cookie
            if (Request.Cookies["userGuid"] == null)
            {
                //add unique GUID for each user
                Response.Cookies["userGuid"].Value = Guid.NewGuid().ToString();
                Response.Cookies["userGuid"].Expires = DateTime.Now.AddDays(30);
            }
        }

        public static string getGuid()
        {
            var Request = HttpContext.Current.Request;

            //if no GUID cookie
            if (Request.Cookies["userGuid"] == null)
            {
                return "";
            }

            return Request.Cookies["userGuid"].Value;
        }

        public static void migrateResourcesFromCookieToUser()
        {
            migrateTemplates();
            migrateImages();
        }

        public static void migrateTemplates()
        {
            using (GenericRepository repository = new GenericRepository())
            {
                string cookieGuid = CookieGuidAttribute.getGuid();
                var templates = repository.Find<DesignTemplate>(m => m.TemplateCategoryId == UserCategoryId && m.CookieGuid == cookieGuid);

                //loop through the templates of this user (referenced by his GUID) and add a value to the UserID field
                foreach (var template in templates)
                {
                    template.UserId = UserHelper.CurrentUser().UserId;
                }

                repository.UnitOfWork.SaveChanges();
            }
        }

        public static void migrateImages()
        {
            using (GenericRepository repository = new GenericRepository())
            {
                string cookieGuid = CookieGuidAttribute.getGuid();

                var images = repository.Find<DesignImage>(m => m.ImageCategoryId == UserCategoryId && m.CookieGuid == cookieGuid);

                //loop through the images of this user (referenced by his GUID) and add a value to the UserID field
                foreach (var image in images)
                {
                    image.UserId = UserHelper.CurrentUser().UserId;
                }

                repository.UnitOfWork.SaveChanges();
            }
        }
    }
}